from fastapi import APIRouter, HTTPException, Depends, Query

from database.database import SystemPrompt
from database.database_function import get_db
from api.schemas.system_prompt import SystemPromptCreateRequest, SystemPromptUpdateRequest, SystemPromptResponse, SystemPromptListResponse, DeleteResponse


router = APIRouter()


@router.post("/system-prompts", response_model=SystemPromptResponse, summary="新增提示词")
async def create_system_prompt(body: SystemPromptCreateRequest, db=Depends(get_db)):
    try:
        prompt = SystemPrompt(
            title=body.title,
            content=body.content,
            enable_context=bool(body.enable_context or False),
            context_placeholder=body.context_placeholder
        )
        db.add(prompt)
        db.commit()
        db.refresh(prompt)
        return SystemPromptResponse(
            system_prompt_id=prompt.system_prompt_id,
            title=prompt.title,
            content=prompt.content,
            enable_context=getattr(prompt, 'enable_context', False),
            context_placeholder=getattr(prompt, 'context_placeholder', None),
            created_time=prompt.created_time,
            updated_time=prompt.updated_time
        )
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建提示词失败: {str(e)}")


@router.get("/system-prompts", response_model=SystemPromptListResponse, summary="提示词列表")
async def list_system_prompts(page: int = Query(1, ge=1), page_size: int = Query(10, ge=1, le=100), db=Depends(get_db)):
    try:
        total = db.query(SystemPrompt).count()
        items = db.query(SystemPrompt).order_by(SystemPrompt.updated_time.desc()).offset((page-1)*page_size).limit(page_size).all()
        prompts = [SystemPromptResponse(
            system_prompt_id=p.system_prompt_id,
            title=p.title,
            content=p.content,
            enable_context=getattr(p, 'enable_context', False),
            context_placeholder=getattr(p, 'context_placeholder', None),
            created_time=p.created_time,
            updated_time=p.updated_time
        ) for p in items]
        return SystemPromptListResponse(
            success=True,
            prompts=prompts,
            total_count=total,
            page=page,
            page_size=page_size,
            total_pages=(total + page_size - 1)//page_size
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取提示词列表失败: {str(e)}")


@router.get("/system-prompts/{prompt_id}", response_model=SystemPromptResponse, summary="提示词详情")
async def get_system_prompt(prompt_id: int, db=Depends(get_db)):
    p = db.query(SystemPrompt).filter(SystemPrompt.system_prompt_id == prompt_id).first()
    if not p:
        raise HTTPException(status_code=404, detail="提示词不存在")
    return SystemPromptResponse(
        system_prompt_id=p.system_prompt_id,
        title=p.title,
        content=p.content,
        enable_context=getattr(p, 'enable_context', False),
        context_placeholder=getattr(p, 'context_placeholder', None),
        created_time=p.created_time,
        updated_time=p.updated_time
    )


@router.patch("/system-prompts/{prompt_id}", response_model=SystemPromptResponse, summary="更新提示词")
async def update_system_prompt(prompt_id: int, body: SystemPromptUpdateRequest, db=Depends(get_db)):
    try:
        p = db.query(SystemPrompt).filter(SystemPrompt.system_prompt_id == prompt_id).first()
        if not p:
            raise HTTPException(status_code=404, detail="提示词不存在")
        if body.title is not None:
            p.title = body.title
        if body.content is not None:
            p.content = body.content
        if body.enable_context is not None:
            p.enable_context = bool(body.enable_context)
        if body.context_placeholder is not None:
            p.context_placeholder = body.context_placeholder
        db.commit()
        db.refresh(p)
        return SystemPromptResponse(
            system_prompt_id=p.system_prompt_id,
            title=p.title,
            content=p.content,
            enable_context=getattr(p, 'enable_context', False),
            context_placeholder=getattr(p, 'context_placeholder', None),
            created_time=p.created_time,
            updated_time=p.updated_time
        )
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新提示词失败: {str(e)}")


@router.delete("/system-prompts/{prompt_id}", response_model=DeleteResponse, summary="删除提示词")
async def delete_system_prompt(prompt_id: int, db=Depends(get_db)):
    try:
        p = db.query(SystemPrompt).filter(SystemPrompt.system_prompt_id == prompt_id).first()
        if not p:
            raise HTTPException(status_code=404, detail="提示词不存在")
        db.delete(p)
        db.commit()
        return DeleteResponse(success=True, message="已删除")
    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除提示词失败: {str(e)}")


